<template>
  <div class="app-container">
    <!-- 工单列表 -->
    <div class="ticket-list-container">
      <div class="filter-container">
        <el-input
          v-model="listQuery.keyword"
          placeholder="搜索工单名称"
          style="width: 200px;"
          class="filter-item"
          clearable
          @keyup.enter.native="handleFilter"
        />
        <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 120px" class="filter-item" @change="handleFilter">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="listQuery.priority" placeholder="优先级" clearable style="width: 120px" class="filter-item" @change="handleFilter">
          <el-option label="特急" :value="2" />
          <el-option label="紧急" :value="1" />
          <el-option label="普通" :value="0" />
          <el-option label="系统自动" :value="-1" />
        </el-select>
        <el-radio-group v-model="listQuery.scope" class="filter-item" style="margin-left: 10px;" @change="handleFilter">
          <el-radio-button label="all">所有</el-radio-button>
          <el-radio-button label="my">待我处理</el-radio-button>
        </el-radio-group>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
          创建工单
        </el-button>
      </div>

      <!-- 工单列表 -->
      <div v-loading="listLoading" class="ticket-list">
        <div v-if="list.length === 0" class="empty-data">
          暂无数据
        </div>
        <div
          v-for="ticket in list"
          :key="ticket.id"
          class="ticket-item"
          :class="{ 'ticket-active': selectedTicketId === ticket.id }"
          @click="handleRowClick(ticket)"
        >
          <div class="ticket-title">{{ ticket.name }}</div>
          <div v-if="ticket.crmorder_data" class="order-info">
            <span class="order-label">关联订单:</span>
            <span class="order-name" @click.stop="handleOpenOrderDetail(ticket.crmorder_data)">
              {{ ticket.crmorder_data.name }}
              <span class="order-no">({{ ticket.crmorder_data.order_no }})</span>
            </span>
          </div>
          <div class="ticket-info">
            <el-select
              v-model="ticket.status"
              size="mini"
              placeholder="状态"
              class="status-select"
              :class="ticket.status + '-status'"
              @change="(value) => handleStatusChange(ticket, value)"
              @click.stop
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span :style="{ color: getStatusColor(item.value) }">{{ item.label }}</span>
              </el-option>
            </el-select>
            <el-select
              v-model="ticket.priority"
              size="mini"
              placeholder="优先级"
              class="priority-select"
              :class="'priority-' + ticket.priority + '-status'"
              @change="(value) => handlePriorityChange(ticket, value)"
              @click.stop
            >
              <el-option label="特急" :value="2">
                <span style="color: #F56C6C">特急</span>
              </el-option>
              <el-option label="紧急" :value="1">
                <span style="color: #E6A23C">紧急</span>
              </el-option>
              <el-option label="普通" :value="0">
                <span style="color: #909399">普通</span>
              </el-option>
              <el-option label="系统自动" :value="-1">
                <span style="color: #292828">系统自动</span>
              </el-option>
            </el-select>
            <el-tag size="mini" :type="statusTypeMap[ticket.status]">{{ ticket.status_display }}</el-tag>
            <el-tag size="mini" :type="priorityTypeMap[ticket.priority]" class="ml-5">
              {{ ticket.priority === 0 ? '普通' : (ticket.priority === 1 ? '紧急' : '特急') }}
            </el-tag>
            <span class="ml-5">负责人: {{ ticket.assignee_name || '未分配' }}</span>
            <span class="ml-5">创建人: {{ ticket.creator_name }}</span>
            <span class="ml-5">更新时间: {{ ticket.update_at_short }}</span>
            <span class="ml-5 deadline-info">
              截止时间: {{ ticket.end_at ? formatDateTime(ticket.end_at) : '未设置' }}
              <el-tooltip content="修改截止时间" placement="top">
                <i class="el-icon-time set-deadline-icon" @click.stop="openDeadlineDialog(ticket)" />
              </el-tooltip>
            </span>
            <div class="ticket-actions">
              <el-button type="text" size="mini" @click.stop="handleShowComments(ticket)">
                <i class="el-icon-chat-dot-square" /> 消息
              </el-button>
              <el-button type="text" size="mini" @click.stop="handleUpdate(ticket)">
                <i class="el-icon-edit" /> 编辑
              </el-button>
              <el-button type="text" size="mini" class="danger-text" @click.stop="handleDelete(ticket)">
                <i class="el-icon-delete" /> 删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <el-pagination
        v-show="total>0"
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 工单表单对话框 -->
    <crm-ticket-form
      :visible.sync="ticketFormVisible"
      :status="dialogStatus"
      :ticket-data="currentTicketData"
      @close="ticketFormVisible = false"
      @success="handleTicketFormSuccess"
    />

    <!-- 工单评论抽屉 -->
    <crm-ticket-comments
      :ticket-id="selectedTicketId"
      :visible.sync="commentsDrawerVisible"
      @comment-added="refreshTicketDetails"
      @close="commentsDrawerVisible = false"
    />

    <!-- 订单详情抽屉 -->
    <crm-order-detail
      :order_data="currentOrder"
      :order-states="orderStates"
      :show-able="orderDetailVisible"
      @close="orderDetailVisible=false"
    />

    <!-- 添加截止时间修改对话框 -->
    <el-dialog
      title="修改截止时间"
      :visible.sync="deadlineDialogVisible"
      width="30%"
      append-to-body
    >
      <el-form :model="deadlineForm" label-width="100px">
        <el-form-item label="截止时间">
          <el-date-picker
            v-model="deadlineForm.end_at"
            type="datetime"
            placeholder="选择截止时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deadlineDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submittingDeadline" @click="updateDeadline">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Put, Delete, GetStatusOptions } from '@/api/crm/ticket'
import { Get as GetOrderStates } from '@/api/crm/crmorderstate'
import waves from '@/directive/waves'
import CrmTicketComments from './elements/crmticketcomments'
import CrmOrderDetail from './elements/crmorderdetail'
import CrmTicketForm from './elements/crmticketform'
import qs from 'qs'

export default {
  name: 'CrmTicket',
  components: {
    CrmTicketComments,
    CrmOrderDetail,
    CrmTicketForm
  },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        'open': '开启',
        'hold': '暂停',
        'close': '关闭'
      }
      return statusMap[status]
    },
    truncateText(text, length) {
      if (!text) return ''
      if (text.length <= length) return text
      return text.substring(0, length) + '...'
    }
  },
  data() {
    return {
      // 工单列表
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 10,
        keyword: '',
        status: 'open',
        priority: '',
        scope: 'my'
      },

      // 状态和优先级映射
      statusTypeMap: {
        'open': 'success',
        'hold': 'warning',
        'close': 'info',
        'later': 'warning'
      },
      priorityTypeMap: {
        0: 'info',
        1: 'warning',
        2: 'danger'
      },
      statusOptions: [
        { value: 'open', label: '开启' },
        { value: 'hold', label: '暂停' },
        { value: 'close', label: '关闭' },
        { value: 'later', label: '稍后处理' }
      ],

      // 当前选中的工单ID
      selectedTicketId: null,

      // 评论抽屉控制
      commentsDrawerVisible: false,

      // 工单表单对话框
      ticketFormVisible: false,
      currentTicketData: {},
      dialogStatus: 'create',

      // 订单详情
      orderDetailVisible: false,
      currentOrder: {},
      orderStates: [],

      // 添加截止时间相关数据
      deadlineDialogVisible: false,
      deadlineForm: {
        end_at: null,
        ticketId: null
      },
      submittingDeadline: false
    }
  },
  watch: {
    // 监听路由查询参数变化
    '$route.query': {
      handler(newQuery) {
        this.checkUrlParams()
        this.handleFilter()
      },
      immediate: false
    }
  },
  created() {
    // 检查URL参数并设置搜索关键词
    this.checkUrlParams()

    this.getList()
    // 获取状态选项
    this.getStatusOptions()
    // 获取订单状态选项
    this.getOrderStates()
  },
  methods: {
    // 检查并处理URL参数
    checkUrlParams() {
      // 检查是否有ticket_id参数
      if (this.$route.query.ticket_id) {
        // 将ticket_id设置为搜索关键词
        this.listQuery.keyword = this.$route.query.ticket_id
        console.log('从URL参数设置搜索关键词:', this.$route.query.ticket_id)
      }

      // 检查其他可能的URL参数
      if (this.$route.query.status) {
        this.listQuery.status = this.$route.query.status
      }

      if (this.$route.query.priority !== undefined) {
        this.listQuery.priority = this.$route.query.priority
      }

      if (this.$route.query.scope) {
        this.listQuery.scope = this.$route.query.scope
      }
    },

    // 打开评论抽屉
    handleShowComments(ticket) {
      this.selectedTicketId = ticket.id
      this.commentsDrawerVisible = true
    },

    // 获取工单列表
    getList() {
      this.listLoading = true
      const params = new URLSearchParams()
      params.append('page', this.listQuery.page)
      params.append('pagesize', this.listQuery.pageSize)
      if (this.listQuery.keyword) {
        params.append('kw', this.listQuery.keyword)
      }
      if (this.listQuery.status) {
        params.append('status', this.listQuery.status)
      }
      if (this.listQuery.priority !== '') {
        params.append('priority', this.listQuery.priority)
      }
      // Add only_me parameter if scope is 'my'
      if (this.listQuery.scope === 'my') {
        params.append('only_me', 'true')
      }

      Get(null, params.toString()).then(response => {
        // 对数据进行排序：特急在前，稍后处理在后
        this.list = this.sortTickets(response.data.data)
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },

    // 获取工单状态选项
    getStatusOptions() {
      GetStatusOptions().then(response => {
        if (response.data && response.data.length > 0) {
          this.statusOptions = response.data
        }
      })
    },

    // 获取订单状态选项
    getOrderStates() {
      GetOrderStates(null, qs.stringify({ all: '1' })).then(response => {
        if (response.data && response.data.data) {
          this.orderStates = response.data.data
        }
      }).catch(error => {
        console.error('获取订单状态失败:', error)
      })
    },

    // 搜索过滤
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    // 行点击事件
    handleRowClick(row) {
      this.selectedTicketId = row.id
      this.commentsDrawerVisible = true
    },

    // 刷新当前工单详情
    refreshTicketDetails() {
      this.getList()
    },

    // 处理状态变化
    handleStatusChange(ticket, value) {
      const tempData = {
        id: ticket.id,
        status: value
      }

      // 调用API更新工单状态
      Put(ticket.id, tempData).then(() => {
        // 更新本地状态显示
        const statusOption = this.statusOptions.find(item => item.value === value)
        ticket.status_display = statusOption ? statusOption.label : value

        this.$notify({
          title: '成功',
          message: '工单状态已更新',
          type: 'success',
          duration: 2000
        })
        // 重新获取列表以更新排序
        this.getList()
      }).catch(() => {
        // 如果失败，恢复原来的状态
        this.$notify({
          title: '错误',
          message: '更新工单状态失败',
          type: 'error',
          duration: 2000
        })
        // 重新获取列表以恢复正确状态
        this.getList()
      })
    },

    // 处理优先级变化
    handlePriorityChange(ticket, value) {
      const tempData = {
        id: ticket.id,
        priority: value
      }

      // 调用API更新工单优先级
      Put(ticket.id, tempData).then(() => {
        // 更新本地优先级
        ticket.priority = value

        this.$notify({
          title: '成功',
          message: '工单优先级已更新',
          type: 'success',
          duration: 2000
        })
        // 重新获取列表以更新排序
        this.getList()
      }).catch(() => {
        // 如果失败，恢复原来的优先级
        this.$notify({
          title: '错误',
          message: '更新工单优先级失败',
          type: 'error',
          duration: 2000
        })
        // 重新获取列表以恢复正确状态
        this.getList()
      })
    },

    getStatusColor(status) {
      const colorMap = {
        'open': '#67C23A',
        'hold': '#E6A23C',
        'close': '#909399',
        'later': '#E6A23C'
      }
      return colorMap[status] || '#909399'
    },

    // 工单排序函数：特急在前，稍后处理在后
    sortTickets(tickets) {
      return tickets.sort((a, b) => {
        // 首先按状态排序：稍后处理排在最后
        if (a.status === 'later' && b.status !== 'later') {
          return 1 // a排在后面
        }
        if (b.status === 'later' && a.status !== 'later') {
          return -1 // b排在后面
        }

        // 然后按优先级排序：特急(2)在前，普通(0)在后
        if (a.priority !== b.priority) {
          return b.priority - a.priority // 降序排列
        }

        // 如果状态和优先级都相同，保持原有顺序
        return 0
      })
    },

    // 打开订单详情
    handleOpenOrderDetail(order) {
      this.currentOrder = order
      this.orderDetailVisible = true
    },

    // Handle successful form submission
    handleTicketFormSuccess() {
      this.ticketFormVisible = false
      this.getList()
    },

    // Handle ticket creation event from comments drawer
    handleTicketCreatedFromComment(newTicket) {
      this.getList()
    },

    // 删除工单
    handleDelete(row) {
      this.$confirm('确认删除该工单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除工单成功',
            type: 'success',
            duration: 2000
          })
          // 如果删除的是当前选中的工单，清空当前选中
          if (this.selectedTicketId === row.id) {
            this.selectedTicketId = null
            this.commentsDrawerVisible = false
          }
          this.getList()
        })
      }).catch(() => {
        // 取消删除
      })
    },

    // 添加分页处理方法
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },

    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },

    // 创建工单
    handleCreate() {
      this.currentTicketData = {}
      this.dialogStatus = 'create'
      this.ticketFormVisible = true
    },

    // 编辑工单
    handleUpdate(row) {
      this.currentTicketData = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.ticketFormVisible = true
    },

    // 添加格式化日期时间方法
    formatDateTime(dateTime) {
      if (!dateTime) return '未设置'
      const date = new Date(dateTime)
      return date.toLocaleString()
    },

    // 打开截止时间设置对话框
    openDeadlineDialog(ticket) {
      this.deadlineForm.ticketId = ticket.id
      this.deadlineForm.end_at = ticket.end_at || null
      this.deadlineDialogVisible = true
    },

    // 更新截止时间
    updateDeadline() {
      if (!this.deadlineForm.ticketId) return

      this.submittingDeadline = true

      const tempData = {
        id: this.deadlineForm.ticketId,
        end_at: this.deadlineForm.end_at
      }

      // 调用API更新工单截止时间
      Put(this.deadlineForm.ticketId, tempData)
        .then(() => {
          // 找到并更新列表中对应工单的截止时间
          const ticket = this.list.find(item => item.id === this.deadlineForm.ticketId)
          if (ticket) {
            ticket.end_at = this.deadlineForm.end_at
          }

          this.$notify({
            title: '成功',
            message: '工单截止时间已更新',
            type: 'success',
            duration: 2000
          })

          // 关闭对话框
          this.deadlineDialogVisible = false
        })
        .catch((error) => {
          console.error('更新工单截止时间失败:', error)
          this.$notify({
            title: '错误',
            message: '更新工单截止时间失败',
            type: 'error',
            duration: 2000
          })
        })
        .finally(() => {
          this.submittingDeadline = false
        })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  margin-right: 10px;
}

.ticket-list-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.ticket-list {
  margin-bottom: 20px;
}

.ticket-item {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 15px;
  cursor: pointer;
  transition: background-color 0.3s, box-shadow 0.3s;
}

.ticket-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ticket-active {
  background-color: #ecf5ff;
}

.ticket-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  word-break: break-all;
}

.order-info {
  margin-bottom: 8px;
}

.order-label {
  font-size: 13px;
  color: #909399;
  margin-right: 5px;
}

.order-name {
  font-size: 13px;
  color: #409EFF;
  cursor: pointer;
  margin-right: 5px;
  text-decoration: none;
}

.order-name:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.order-no {
  font-size: 12px;
  color: #909399;
}

.ticket-meta {
  margin: 10px 0;
}

.ticket-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
  margin-bottom: 10px;
  background-color: #f9f9f9;
  padding: 8px;
  border-radius: 4px;
  border-left: 3px solid #e6e6e6;
}

.ticket-info {
  font-size: 13px;
  color: #909399;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding-top: 10px;
  border-top: 1px dashed #ebeef5;
}

.status-select {
  width: 90px;
  margin-right: 10px;
}

.priority-select {
  width: 80px;
  margin-right: 10px;
}

/* 自定义状态选择框样式 */
.ticket-item >>> .el-select .el-input__inner {
  border-color: transparent;
  background-color: rgba(0, 0, 0, 0.05);
}

/* 优先级选择框也使用相同的无边框样式 */
.ticket-item >>> .priority-select .el-input__inner {
  border-color: transparent;
  background-color: rgba(0, 0, 0, 0.05);
}

.ticket-item >>> .el-select.open-status .el-input__inner {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
  border-left: 3px solid #67C23A;
}

.ticket-item >>> .el-select.hold-status .el-input__inner {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
  border-left: 3px solid #E6A23C;
}

.ticket-item >>> .el-select.close-status .el-input__inner {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
  border-left: 3px solid #909399;
}

.ticket-item >>> .el-select.later-status .el-input__inner {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
  border-left: 3px solid #E6A23C;
}

/* 自定义优先级选择框样式 */
.ticket-item >>> .el-select.priority-0-status .el-input__inner {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
  border-left: 3px solid #909399;
}

.ticket-item >>> .el-select.priority-1-status .el-input__inner {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
  border-left: 3px solid #E6A23C;
}

.ticket-item >>> .el-select.priority-2-status .el-input__inner {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
  border-left: 3px solid #F56C6C;
}

.ticket-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.ml-5 {
  margin-left: 5px;
}

.danger-text {
  color: #F56C6C;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 添加截止时间相关样式 */
.deadline-info {
  display: flex;
  align-items: center;
}

.set-deadline-icon {
  margin-left: 5px;
  color: #409EFF;
  cursor: pointer;
  transition: color 0.3s;
}

.set-deadline-icon:hover {
  color: #66b1ff;
}
</style>
